import json
# 读json文件
import os.path


def read_file(file_path):
    with open(file_path, 'r') as f:
        data = json.load(f)
    return data

# 写json文件,全量覆盖
def write_file(file_path, data):
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False)

# 写json文件，追加数据
def append_file(file_path, data):
    with open(file_path, 'a', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

# 写json文件，key不存在则插入，存在则更新
def write_or_update(file_path, key, json_data):
    if not os.path.exists(file_path) or os.path.getsize(file_path) == 0:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write('[]')
    if os.path.getsize(file_path) == 0:
        write_file(file_path, json_data)
        return
    with open(file_path, 'r', encoding='utf-8') as file:
        file_json_data = json.load(file)
        row_number = find_target_row(file_json_data, key, json_data[0])
        result = []
        if row_number != -1:        # 找到对应记录行号，则更新当前行
              result = update_target_row(file_json_data, row_number, json_data[0])
        else:                       # 找不到对应记录行号，则在最后插入记录
            result = file_json_data
            result.append(json_data[0])
        write_file(file_path, result)


def find_target_row(json_data, key, data):
    """
    找到目标json数据, 返回行号
    :param json_data: 读到的json文件转换出来的json数据
    :param key: 查找的关键字，json_data种唯一
    :param data: 要查找的目标json数据
    :return: 行号
    """
    for i, row in enumerate(json_data):
        if row[key] == data[key]:
            return i
    return -1


def find_target_json(path, key, data):
    """
    找到目标json数据, 返回json格式数据
    :param path: 文件路径
    :param key: 匹配的关键字
    :param data: 目标数据
    :return: json数据
    """
    with open(path, 'r', encoding='utf-8') as file:
        file_json_data = json.load(file)
        for i, row in enumerate(file_json_data):
            if row[key] == data[key]:
                return row
        return []

# 修改目标json数据
def update_target_row(json_data, row_number, target_data):
    json_data[row_number] = target_data
    return json_data